package com.test.demo.base


import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.viewbinding.ViewBinding
import com.test.demo.view.BindingReflex
import com.test.demo.view.FrameView


abstract class BaseDialogFragment<VB : ViewBinding> : DialogFragment(), FrameView<VB> {

    private var _binding: VB? = null
    val mBinding get() = _binding!!
    var mCancelAble: Boolean = true

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?,
    ): View? {
        _binding = BindingReflex.reflexViewBinding(javaClass, layoutInflater)
        return _binding?.root
    }

//    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
//        val dialog = Dialog(requireContext())
//        dialog.setCanceledOnTouchOutside(true)
//        dialog.setCancelable(true)
//        // 设置背景透明
//        dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.RED))
//        // 其他设置..
//        return dialog
//    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initWindow()

        mBinding.initView()
        view.setOnClickListener {
//            if (mCancelAble) {
//                dismiss()
//            }
        }
    }

    override fun show(manager: FragmentManager, tag: String?) {
        if (manager.isDestroyed) return
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            val ft: FragmentTransaction = manager.beginTransaction()
            ft.add(this, tag)
            ft.commitAllowingStateLoss()
        } catch (e: Exception) {
            //同一实例使用不同的tag会异常，这里捕获一下
            e.printStackTrace()
        }
    }

    protected open fun initWindow() {
        val attributes = dialog?.window?.attributes
        if (showInBottom()) {
            attributes?.gravity = Gravity.BOTTOM
        } else {
            attributes?.gravity = Gravity.CENTER
        }
        attributes?.width = WindowManager.LayoutParams.MATCH_PARENT
        attributes?.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialog?.window?.attributes = attributes
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog?.setCanceledOnTouchOutside(mCancelAble)
        dialog?.setCancelable(mCancelAble)
    }

    open fun showInBottom(): Boolean {
        return true
    }

}

